﻿using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FortuneArterial.Site.BusinessLogicLayer.LunceneSearch.Analysis;
using FortuneArterial.Site.BusinessLogicLayer.LunceneSearch.Service;

namespace FortuneArterial.Site.Laboratory.Controllers.Lucene.Net
{
    [DisplayName("音频文件索引")]
    public partial class LuceneDirectoyFileController
        : BaseController
    {
        [HttpGet]
        [DisplayName("音频文件索引")]
        public ActionResult MusicFile()
        {
            return SmartView(new Models.MusicFileEntity());
        }

        [HttpPost]
        public ActionResult MusicFileData(string q, string filed, int page = 1, int rows = 10)
        {
            // perform Lucene search
            var models = String.IsNullOrEmpty(q) ? luceneMusic.GetAllIndexRecords() : luceneMusic.SearchDefault(q, filed);
            return Json(new
            {
                total = models.Count(),
                rows = models.Skip((page - 1) * rows).Take(rows).OrderBy(m => m.FileName)
            });
        }

        [HttpPost]
        [ActionName("MusicFile")]
        public ActionResult PostMusic(string path)
        {
            //Fix Bug: 没有权限访问系统文件夹中的内容，这些文件夹只会存在与分区根目录
            var topDirs = Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly)
                    .Where(m => !m.ToUpper().EndsWith("$RECYCLE.BIN") && !m.ToUpper().EndsWith("SYSTEM VOLUME INFORMATION"))
                    .ToList();
            topDirs.Insert(0, path);

            foreach (var topDir in topDirs)
            {
                luceneMusic.AddUpdateLuceneIndex(
                    Directory.EnumerateFiles(topDir, "*.*",
                        topDir == path ? SearchOption.TopDirectoryOnly : SearchOption.AllDirectories)
                        .Where(MusicFilter)
                        .Select(CreateMsicEntity)
                    );
            }

            return Json(new { Result = true });
        }

        private bool MusicFilter(string path)
        {
            var ext = Path.GetExtension(path);
            if (string.IsNullOrWhiteSpace(ext)) return false;
            //BUG: "ac3 dts" 不受支持
            return "wav wma mpa mp2 m1a m2a mp3 ogg m4a aac mka ra flac ape mpc mod eac3 dtshd wv tak".Split(' ')
                .Any(m => ext.EndsWith(m, StringComparison.OrdinalIgnoreCase));
        }

        private Models.MusicFileEntity CreateMsicEntity(string path)
        {
            return new Models.MusicFileEntity(path);;
        }

        [HttpDelete]
        [ActionName("MusicFile")]
        public ActionResult DeleteMusic(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                luceneMusic.ClearLuceneIndex();
            }
            else
            {
                luceneMusic.ClearLuceneIndexRecord(id);
            }

            return Json(new { Result = true });
        }

        [HttpPut]
        [ActionName("MusicFile")]
        public ActionResult PutMusic(string id)
        {
            return Json(new { Result = true });
        }

        private LuceneService<Models.MusicFileEntity, PanGuAnalyzer> luceneMusic =
            new LuceneService<Models.MusicFileEntity, PanGuAnalyzer>(
                Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"temp\lucene_index\music_file\"));
    }
}